<?php

/**
 * @file
 *   ter_em_demographic_info
 * EM Registration Submits and Validations for Form steps.
 */
function _register_em_demographic_info_submit($form, &$form_state) {
    //return;
    $values = $form_state['values'];

    //set up the user fields
    $fields = array(
        'name' => $values["username"],
        'mail' => $values["email"],
        'pass' => $values["password"],
        'status' => 1,
        'init' => 'email address',
        'roles' => array(
            DRUPAL_AUTHENTICATED_RID => 'authenticated user',
        ),
    );

    $user_account = user_save(NULL, $fields); //Add Data in Drupal user table
    $user_id = $user_account->uid;

    $new_user = db_insert('la_users')->fields(array(
                'user_id' => $user_id,
                'first_name' => $values['first_name'],
                'middle_name' => $values['middle_name'],
                'last_name' => $values['last_name'],
                'aka_first_name' => $values['aka_first_name'],
                'aka_last_name' => $values['aka_last_name'],
                'dob' => $values['dob']['year'] . "-" . $values['dob']['month'] . "-" . $values['dob']['day'],
                'cell_phone' => $values['cell_phone'],
                'phone_number' => $values['phone_number'],
                'marital_status' => $values['marital_status'],
                'gender' => $values['gender'],
                'ethnicity' => $values['ethnicity'],
                'ca_resident' => $values['ca_resident'],
                'discriminator' => "EM",
            ))->execute();

    //Store alternate contact methods in contact_methods methods 
    foreach ($values['alternate_contact'] as $alternate_contact) {
        $carrier = "";
        if (strtolower($alternate_contact) == "texting") {
            $carrier = $values['text_carrier'];
        }

        $contact_method = db_insert('contact_methods')->fields(array(
                    'contact_method_title' => $alternate_contact,
                    'users_user_id' => $user_id,
                    'carrier' => $carrier,
                ))->execute();
    }

    //Login New User
    global $user;
    $uid = user_authenticate($values["username"], $values["password"]);
    $arr = array('name' => $values["username"], 'pass' => $values["password"]);
    if ($uid) {
        $user = user_load($uid);
        user_login_finalize($arr);
    }
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        // AJAX request
    } else {
        drupal_goto('registration/saved');
        exit;
    }
}

function _register_em_address_submit($form, &$form_state) {
    $logged_in_user = getCurrentUser();
    if ($logged_in_user->uid) { // if user is logged in 
        $user_id = $logged_in_user->uid;
        $values = $form_state['values'];
        $form_key = "em_addresses";

        unset($values[$form_key]["add_address"]);
        unset($values[$form_key]["remove_address"]);
        foreach ($values[$form_key] as $address_data) {
            $address = db_insert('addresses')->fields(array(
                        'users_user_id' => $user_id,
                        'mailing_address' => $address_data['mailing_address'],
                        'apartment_number' => $address_data['apt_no'],
                        'city' => $address_data['city'],
                        'state' => $address_data['state'],
                        'zip' => $address_data['zip'],
                        'adults' => $address_data['no_of_adults_address'],
                        'children' => $address_data['no_of_children_address'],
                        'accept_mailings' => $address_data['mail_at_address'],
                    ))->execute();
        }
        if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            // AJAX request
        } else {
            drupal_goto('registration/saved');
            exit;
        }
    }
}

function _register_em_eligibility_submit($form, &$form_state) {
//    $file = file_load($form_state['values']['file']);
//    $ext= ext($file->filename);
//    $fileName= genFileName().'.'.$ext;
//    $file->filename;
//    $file->status = FILE_STATUS_PERMANENT;
//    file_save($file);    
    $logged_in_user = getCurrentUser();
    if ($logged_in_user->uid) { // if user is logged in 
        $user_id = $logged_in_user->uid;
        $values = $form_state['values'];
        $form_key = "em_unions";

        unset($values[$form_key]["add_union"]);
        unset($values[$form_key]["remove_union"]);
        foreach ($values[$form_key] as $union_data) {
            $union = db_insert('users_has_unions')->fields(array(
                        'user_id' => $user_id,
                        'union_id' => $union_data['union_id'],
                        'union_number' => $union_data['union_no'],
                    ))->execute();
        }
        $agency = db_insert('agencies')->fields(array(
                    'users_user_id' => $user_id,
                    'agency_name' => $values['agency'],
                    'agent_name' => $values['agent_name'],
                    'agency_phone' => $values['agent_phone'],
                ))->execute();
        
    }
    if (isset($form_state['triggering_element']) && $form_state['triggering_element']['#value'] == "Save Draft" ) {
        drupal_goto('registration/saved');
    }
}

function _register_em_education_submit($form, &$form_state) {
    $logged_in_user = getCurrentUser();
    if ($logged_in_user->uid) { // if user is logged in 
        $user_id = $logged_in_user->uid;
        $values = $form_state['values'];
        $form_key = "em_schools";

        unset($values[$form_key]["add_school"]);
        unset($values[$form_key]["remove_school"]);
        foreach ($values[$form_key] as $school_data) {
            $school = db_insert('schools')->fields(array(
                        'users_user_id' => $user_id,
                        'school_name' => $school_data['school_name'],
                        'city' => $school_data['school_city'],
                        'state' => $school_data['school_state'],
                        'zip' => $school_data['school_zip'],
                        'school_type' => $school_data['school_type'],
                        'years_spent' => $school_data['school_years'],
                        'graduation_level' => $school_data['school_grade_level'],
                        'is_graduated' => $school_data['has_graduated'],
                    ))->execute();
        }
    }
    if (isset($form_state['triggering_element']) && $form_state['triggering_element']['#value'] == "Save Draft" ) {
        drupal_goto('registration/saved');
    }
}

function _register_em_waivers_releases_submit($form, &$form_state) {
    $logged_in_user = getCurrentUser();
    if ($logged_in_user->uid) { // if user is logged in 
        $user_id = $logged_in_user->uid;
        $values = $form_state['values'];
        $form_key = "em_waivers_releases";

        $union = db_insert('waivers_and_releases')->fields(array(
                    'users_user_id' => $user_id,
                    'code_of_conduct_confirmation' => !empty($values['code_of_conduct']) ? 1 : 0,
                    'photo_release_confirmation' => !empty($values['photo_release']) ? 1 : 0,
                    'video_release_confirmation' => !empty($values['video_release']) ? 1 : 0,
                    'emergency_contact_first' => $values['emergency_contact']['emergency_contact_first'],
                    'emergency_contact_last' => $values['emergency_contact']['emergency_contact_last'],
                    'emergency_phone' => $values['emergency_contact']['emergency_phone'],
                    'emergency_address' => $values['emergency_contact']['emergency_address'],
                    'emergency_apartment' => $values['emergency_contact']['emergency_apt'],
                    'emergency_city' => $values['emergency_contact']['emergency_city'],
                    'emergency_state' => $values['emergency_contact']['emergency_state'],
                    'emergency_zip' => $values['emergency_contact']['emergency_zip'],
                    'relationship_to_participant' => $values['emergency_contact']['relationship_to_participant'],
                    'insurance_name' => $values['name_of_insurance'],
                    'medical_insurance_number' => $values['medical_insurance_no'],
                    'any_medical_issue' => !empty($values['disabilities']) ? 1 : 0,
                    'medical_issue_explanation' => !empty($values['disability_explanation']) ? 1 : 0,
                    'any_alergy' => !empty($values['medication_allergy']) ? 1 : 0,
                    'allergy_explanation' => $values['allergy_explanation'],
                    'any_medication' => $values['taking_medication'],
                    'medication_explanation' => !empty($values['medication_explanation']) ? 1 : 0,
                ))->execute();
    }
    if (isset($form_state['triggering_element']) && $form_state['triggering_element']['#value'] == "Save Draft" ) {
        drupal_goto('registration/saved');
    }
}

function _register_em_additional_info_submit($form, &$form_state) {
    $logged_in_user = getCurrentUser();
    if ($logged_in_user->uid) { // if user is logged in 
        $user_id = $logged_in_user->uid;
        $values = $form_state['values'];

        $user = db_update('la_users')->fields(array(
                    'more_info' => !empty($values['more_info']) ? 1 : 0,
                    'education_counseling' => !empty($values['education_counseling']) ? 1 : 0,
                    'family_counseling' => !empty($values['family_counseling']) ? 1 : 0,
                    'referred_by_google' => !empty($values['heard_from']["Google"]) ? 1 : 0,
                    'referred_by_friend' => !empty($values['heard_from']["Friend"]) ? 1 : 0
                ))
                ->condition('user_id', $user_id)
                ->execute();
    }
}
